<template>
  <div class="security-baseline-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h2>安全基线配置管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="createBaseline">
          <el-icon><Plus /></el-icon> 创建基线
        </el-button>
        <el-button @click="importBaseline">
          <el-icon><Upload /></el-icon> 导入基线
        </el-button>
        <el-button @click="refreshBaselines">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ totalBaselines }}</div>
          <div class="stat-label">基线总数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ activeBaselines }}</div>
          <div class="stat-label">活跃基线</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ compliantSystems }}%</div>
          <div class="stat-label">合规率</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ pendingTasks }}</div>
          <div class="stat-label">待处理任务</div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和筛选区 -->
    <div class="search-filter-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="基线名称">
          <el-input
            v-model="searchForm.name"
            placeholder="输入基线名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="基线类型">
          <el-select v-model="searchForm.type" placeholder="选择基线类型" clearable>
            <el-option label="操作系统" value="os" />
            <el-option label="数据库" value="database" />
            <el-option label="Web服务器" value="web_server" />
            <el-option label="应用服务" value="application" />
            <el-option label="网络设备" value="network_device" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="活跃" value="active" />
            <el-option label="禁用" value="disabled" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 基线列表表格 -->
    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span>基线列表</span>
          <div class="header-actions">
            <el-dropdown @command="handleBatchAction">
              <el-button>批量操作<el-icon class="el-icon--right"><ArrowDown /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="activate">激活所选基线</el-dropdown-item>
                  <el-dropdown-item command="deactivate">禁用所选基线</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除所选基线</el-dropdown-item>
                  <el-dropdown-item command="export" divided>导出所选基线</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="filteredBaselines"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="基线ID" width="180" />
          <el-table-column prop="name" label="基线名称">
            <template #default="scope">
              <a href="javascript:void(0)" @click="viewBaselineDetails(scope.row)">{{ scope.row.name }}</a>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="基线类型" width="120">
            <template #default="scope">
              <el-tag :type="getTypeTagType(scope.row.type)">
                {{ getTypeName(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="版本" width="80" />
          <el-table-column prop="controlsCount" label="控制项数" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastUpdated" label="最后更新时间" width="180" />
          <el-table-column prop="createdBy" label="创建人" width="120" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="deployBaseline(scope.row)">部署</el-button>
              <el-button size="small" @click="editBaseline(scope.row)">编辑</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="viewCompliance(scope.row)">合规性检查</el-dropdown-item>
                    <el-dropdown-item @click="exportBaseline(scope.row)">导出基线</el-dropdown-item>
                    <el-dropdown-item @click="cloneBaseline(scope.row)">克隆基线</el-dropdown-item>
                    <el-dropdown-item @click="deleteBaseline(scope.row)" divided type="danger">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredBaselines.length"
        />
      </div>
    </el-card>

    <!-- 基线详情对话框 -->
    <el-dialog
      v-model="baselineDetailsVisible"
      :title="currentBaseline ? `基线详情 - ${currentBaseline.name}` : '基线详情'"
      width="70%"
      @close="closeBaselineDetails"
    >
      <div v-if="currentBaseline" class="baseline-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="基线ID">{{ currentBaseline.id }}</el-descriptions-item>
          <el-descriptions-item label="基线名称">{{ currentBaseline.name }}</el-descriptions-item>
          <el-descriptions-item label="基线类型">{{ getTypeName(currentBaseline.type) }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ currentBaseline.version }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ currentBaseline.description }}</el-descriptions-item>
          <el-descriptions-item label="控制项数">{{ currentBaseline.controlsCount }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getStatusName(currentBaseline.status) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentBaseline.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="最后更新时间">{{ currentBaseline.lastUpdated }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ currentBaseline.createdBy }}</el-descriptions-item>
          <el-descriptions-item label="适用平台">{{ currentBaseline.supportedPlatforms.join(', ') }}</el-descriptions-item>
        </el-descriptions>

        <h3 class="section-title">控制项列表</h3>
        <el-table :data="currentBaseline.controls" style="width: 100%" stripe>
          <el-table-column prop="id" label="控制ID" width="120" />
          <el-table-column prop="name" label="控制项名称" />
          <el-table-column prop="severity" label="严重程度" width="100">
            <template #default="scope">
              <el-tag :type="getSeverityTagType(scope.row.severity)">
                {{ getSeverityName(scope.row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column prop="checkMethod" label="检查方法" width="150" />
          <el-table-column prop="remediation" label="修复建议" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>

    <!-- 创建/编辑基线对话框 -->
    <el-dialog
      v-model="createEditVisible"
      :title="isEditing ? '编辑基线' : '创建基线'"
      width="60%"
      @close="closeCreateEdit"
    >
      <el-form
        ref="baselineFormRef"
        :model="baselineForm"
        :rules="baselineFormRules"
        label-width="100px"
      >
        <el-form-item label="基线名称" prop="name">
          <el-input v-model="baselineForm.name" placeholder="请输入基线名称" />
        </el-form-item>
        <el-form-item label="基线类型" prop="type">
          <el-select v-model="baselineForm.type" placeholder="请选择基线类型">
            <el-option label="操作系统" value="os" />
            <el-option label="数据库" value="database" />
            <el-option label="Web服务器" value="web_server" />
            <el-option label="应用服务" value="application" />
            <el-option label="网络设备" value="network_device" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="baselineForm.description"
            type="textarea"
            placeholder="请输入基线描述"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="适用平台" prop="supportedPlatforms">
          <el-checkbox-group v-model="baselineForm.supportedPlatforms">
            <el-checkbox v-for="platform in availablePlatforms" :key="platform.value" :label="platform.value">
              {{ platform.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <h3 class="section-title">控制项管理</h3>
      <div class="controls-management">
        <el-button type="primary" @click="addControl">
          <el-icon><Plus /></el-icon> 添加控制项
        </el-button>
        <el-table :data="baselineForm.controls" style="width: 100%; margin-top: 15px" stripe>
          <el-table-column prop="name" label="控制项名称" />
          <el-table-column prop="severity" label="严重程度" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.severity">
                <el-option label="严重" value="critical" />
                <el-option label="高危" value="high" />
                <el-option label="中危" value="medium" />
                <el-option label="低危" value="low" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="editControl(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="removeControl(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="closeCreateEdit">取消</el-button>
        <el-button type="primary" :loading="formLoading" @click="saveBaseline">
          {{ isEditing ? '更新基线' : '创建基线' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 部署基线对话框 -->
    <el-dialog
      v-model="deployBaselineVisible"
      title="部署基线"
      width="50%"
    >
      <el-form
        ref="deployFormRef"
        :model="deployForm"
        :rules="deployFormRules"
        label-width="100px"
      >
        <el-form-item label="目标系统" prop="targetSystems">
          <el-checkbox-group v-model="deployForm.targetSystems">
            <el-checkbox v-for="system in availableSystems" :key="system.id" :label="system.id">
              {{ system.name }} - {{ system.type }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="部署模式" prop="deployMode">
          <el-radio-group v-model="deployForm.deployMode">
            <el-radio label="audit">仅审计（不修改配置）</el-radio>
            <el-radio label="enforce">强制执行（自动修复）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行时间" prop="executeTime">
          <el-radio-group v-model="deployForm.executeOption">
            <el-radio label="immediate">立即执行</el-radio>
            <el-radio label="scheduled">定时执行</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="deployForm.executeOption === 'scheduled'"
            v-model="deployForm.scheduledTime"
            type="datetime"
            style="margin-top: 10px; width: 100%"
            placeholder="选择执行时间"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="deployBaselineVisible = false">取消</el-button>
        <el-button type="primary" :loading="deployLoading" @click="confirmDeploy">确认部署</el-button>
      </template>
    </el-dialog>

    <!-- 合规性检查结果对话框 -->
    <el-dialog
      v-model="complianceResultVisible"
      :title="`合规性检查结果 - ${complianceResultBaselineName}`"
      width="70%"
    >
      <div v-if="complianceResult" class="compliance-result">
        <div class="compliance-summary">
          <h3>检查摘要</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="检查时间">{{ complianceResult.checkTime }}</el-descriptions-item>
            <el-descriptions-item label="目标系统">{{ complianceResult.targetSystem }}</el-descriptions-item>
            <el-descriptions-item label="总检查项">{{ complianceResult.totalChecks }}</el-descriptions-item>
            <el-descriptions-item label="合规项">{{ complianceResult.compliantChecks }}</el-descriptions-item>
            <el-descriptions-item label="不合规项">{{ complianceResult.nonCompliantChecks }}</el-descriptions-item>
            <el-descriptions-item label="合规率">{{ complianceResult.complianceRate }}%</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="compliance-chart">
          <h3>合规性分布图</h3>
          <div ref="complianceChart" style="height: 300px"></div>
        </div>

        <h3>详细检查结果</h3>
        <el-table :data="complianceResult.checkDetails" style="width: 100%" stripe>
          <el-table-column prop="controlId" label="控制项ID" width="120" />
          <el-table-column prop="controlName" label="控制项名称" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'compliant' ? 'success' : 'danger'">
                {{ scope.row.status === 'compliant' ? '合规' : '不合规' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="actualValue" label="当前值" show-overflow-tooltip />
          <el-table-column prop="expectedValue" label="期望值" show-overflow-tooltip />
          <el-table-column prop="severity" label="严重程度" width="100">
            <template #default="scope">
              <el-tag :type="getSeverityTagType(scope.row.severity)">
                {{ getSeverityName(scope.row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remediation" label="修复建议" show-overflow-tooltip />
        </el-table>
      </div>

      <template #footer>
        <el-button @click="complianceResultVisible = false">关闭</el-button>
        <el-button @click="exportComplianceReport">导出报告</el-button>
        <el-button type="primary" @click="remediateNonCompliant">修复不合规项</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Plus,
  Upload,
  Refresh,
  Search,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const formLoading = ref(false)
const deployLoading = ref(false)
const searchForm = ref({
  name: '',
  type: '',
  status: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const selectedBaselines = ref([])
const baselineDetailsVisible = ref(false)
const currentBaseline = ref(null)
const createEditVisible = ref(false)
const isEditing = ref(false)
const deployBaselineVisible = ref(false)
const complianceResultVisible = ref(false)
const complianceResultBaselineName = ref('')
const complianceResult = ref(null)
const complianceChart = ref(null)

// 基线表单数据
const baselineForm = ref({
  id: '',
  name: '',
  type: '',
  description: '',
  version: '1.0',
  supportedPlatforms: [],
  controls: []
})

// 基线表单验证规则
const baselineFormRules = ref({
  name: [
    { required: true, message: '请输入基线名称', trigger: 'blur' },
    { min: 1, max: 100, message: '名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择基线类型', trigger: 'change' }
  ],
  supportedPlatforms: [
    { required: true, message: '请选择至少一个适用平台', trigger: 'change' }
  ]
})

// 部署表单数据
const deployForm = ref({
  targetSystems: [],
  deployMode: 'audit',
  executeOption: 'immediate',
  scheduledTime: null
})

// 部署表单验证规则
const deployFormRules = ref({
  targetSystems: [
    { required: true, message: '请选择至少一个目标系统', trigger: 'change' }
  ]
})

// 可用平台列表
const availablePlatforms = ref([
  { label: 'Windows Server 2016', value: 'windows_server_2016' },
  { label: 'Windows Server 2019', value: 'windows_server_2019' },
  { label: 'Windows Server 2022', value: 'windows_server_2022' },
  { label: 'CentOS 7', value: 'centos_7' },
  { label: 'CentOS 8', value: 'centos_8' },
  { label: 'Ubuntu 18.04', value: 'ubuntu_1804' },
  { label: 'Ubuntu 20.04', value: 'ubuntu_2004' },
  { label: 'Ubuntu 22.04', value: 'ubuntu_2204' },
  { label: 'MySQL 5.7', value: 'mysql_57' },
  { label: 'MySQL 8.0', value: 'mysql_80' },
  { label: 'SQL Server 2017', value: 'sqlserver_2017' },
  { label: 'SQL Server 2019', value: 'sqlserver_2019' },
  { label: 'Oracle 19c', value: 'oracle_19c' },
  { label: 'PostgreSQL 12', value: 'postgresql_12' },
  { label: 'PostgreSQL 14', value: 'postgresql_14' },
  { label: 'Apache 2.4', value: 'apache_24' },
  { label: 'Nginx 1.18', value: 'nginx_118' },
  { label: 'Nginx 1.20', value: 'nginx_120' },
  { label: 'Tomcat 9', value: 'tomcat_9' },
  { label: 'WebSphere 9', value: 'websphere_9' },
  { label: 'WebLogic 12c', value: 'weblogic_12c' },
  { label: 'F5 BIG-IP', value: 'f5_bigip' },
  { label: 'Cisco IOS', value: 'cisco_ios' },
  { label: 'Huawei VRP', value: 'huawei_vrp' }
])

// 可用系统列表
const availableSystems = ref([
  { id: 'SERVER-001', name: 'Web服务器-01', type: 'windows_server_2019' },
  { id: 'SERVER-002', name: '应用服务器-01', type: 'centos_7' },
  { id: 'SERVER-003', name: '数据库服务器-01', type: 'windows_server_2019' },
  { id: 'SERVER-004', name: 'Web服务器-02', type: 'ubuntu_2004' },
  { id: 'SERVER-005', name: '应用服务器-02', type: 'centos_8' },
  { id: 'DB-001', name: '主数据库-01', type: 'mysql_80' },
  { id: 'DB-002', name: '从数据库-01', type: 'mysql_80' },
  { id: 'DB-003', name: 'SQL Server-01', type: 'sqlserver_2019' },
  { id: 'NET-001', name: '防火墙-01', type: 'cisco_ios' },
  { id: 'NET-002', name: '负载均衡器-01', type: 'f5_bigip' }
])

// 模拟基线数据
const mockBaselines = [
  {
    id: 'BASELINE-OS-001',
    name: 'Windows Server 2019 安全基线',
    type: 'os',
    version: '1.2',
    description: '基于CIS标准的Windows Server 2019安全基线配置',
    controlsCount: 156,
    status: 'active',
    createdAt: '2023-11-15 09:30:00',
    lastUpdated: '2024-01-10 14:20:00',
    createdBy: '张三',
    supportedPlatforms: ['windows_server_2019'],
    controls: [
      {
        id: 'CTRL-OS-001',
        name: '启用Windows防火墙',
        severity: 'critical',
        description: '确保Windows防火墙在所有网络配置文件上都已启用',
        checkMethod: 'powershell',
        remediation: '使用组策略或PowerShell启用Windows防火墙'
      },
      {
        id: 'CTRL-OS-002',
        name: '配置账户锁定策略',
        severity: 'high',
        description: '设置账户锁定阈值为5次失败尝试，锁定时间为30分钟',
        checkMethod: 'registry',
        remediation: '修改账户锁定策略设置'
      }
      // 更多控制项...
    ]
  },
  {
    id: 'BASELINE-DB-001',
    name: 'MySQL 8.0 安全基线',
    type: 'database',
    version: '1.1',
    description: 'MySQL 8.0数据库服务器安全加固配置基线',
    controlsCount: 89,
    status: 'active',
    createdAt: '2023-12-05 11:45:00',
    lastUpdated: '2024-01-08 10:15:00',
    createdBy: '李四',
    supportedPlatforms: ['mysql_80'],
    controls: [
      {
        id: 'CTRL-DB-001',
        name: '删除匿名用户',
        severity: 'critical',
        description: '确保MySQL中不存在匿名用户账户',
        checkMethod: 'sql',
        remediation: '执行DROP USER命令删除匿名用户'
      },
      {
        id: 'CTRL-DB-002',
        name: '禁用远程root登录',
        severity: 'critical',
        description: '确保root用户只能从本地登录',
        checkMethod: 'sql',
        remediation: '移除允许远程root登录的账户'
      }
      // 更多控制项...
    ]
  },
  {
    id: 'BASELINE-WEB-001',
    name: 'Nginx 安全基线',
    type: 'web_server',
    version: '1.0',
    description: 'Nginx Web服务器安全加固配置基线',
    controlsCount: 45,
    status: 'active',
    createdAt: '2023-12-20 16:20:00',
    lastUpdated: '2024-01-05 15:30:00',
    createdBy: '王五',
    supportedPlatforms: ['nginx_118', 'nginx_120'],
    controls: [
      {
        id: 'CTRL-WEB-001',
        name: '禁用版本信息',
        severity: 'medium',
        description: '确保Nginx不显示版本信息',
        checkMethod: 'configuration',
        remediation: '在nginx.conf中设置server_tokens off'
      },
      {
        id: 'CTRL-WEB-002',
        name: '配置HTTPS',
        severity: 'high',
        description: '确保使用TLS 1.2或更高版本，禁用不安全的密码套件',
        checkMethod: 'configuration',
        remediation: '配置SSL/TLS参数和密码套件'
      }
      // 更多控制项...
    ]
  },
  {
    id: 'BASELINE-APP-001',
    name: 'Tomcat 9 安全基线',
    type: 'application',
    version: '1.1',
    description: 'Apache Tomcat 9应用服务器安全加固配置基线',
    controlsCount: 67,
    status: 'active',
    createdAt: '2023-11-25 13:10:00',
    lastUpdated: '2024-01-12 09:45:00',
    createdBy: '赵六',
    supportedPlatforms: ['tomcat_9'],
    controls: [
      {
        id: 'CTRL-APP-001',
        name: '移除默认管理账户',
        severity: 'critical',
        description: '删除或修改默认的Tomcat管理账户',
        checkMethod: 'file',
        remediation: '修改tomcat-users.xml文件，删除或更改默认账户'
      },
      {
        id: 'CTRL-APP-002',
        name: '限制管理界面访问',
        severity: 'high',
        description: '限制管理界面只能从特定IP访问',
        checkMethod: 'configuration',
        remediation: '在server.xml中配置访问控制'
      }
      // 更多控制项...
    ]
  },
  {
    id: 'BASELINE-NET-001',
    name: '网络设备安全基线',
    type: 'network_device',
    version: '1.0',
    description: '通用网络设备安全加固配置基线',
    controlsCount: 54,
    status: 'disabled',
    createdAt: '2023-12-10 10:00:00',
    lastUpdated: '2023-12-15 11:30:00',
    createdBy: '孙七',
    supportedPlatforms: ['cisco_ios', 'huawei_vrp'],
    controls: [
      {
        id: 'CTRL-NET-001',
        name: '启用SSH，禁用Telnet',
        severity: 'critical',
        description: '确保使用SSH进行远程管理，禁用不安全的Telnet协议',
        checkMethod: 'cli',
        remediation: '配置SSH，禁用Telnet服务'
      },
      {
        id: 'CTRL-NET-002',
        name: '配置ACL限制访问',
        severity: 'high',
        description: '配置访问控制列表限制对管理接口的访问',
        checkMethod: 'cli',
        remediation: '创建并应用适当的ACL规则'
      }
      // 更多控制项...
    ]
  }
]

// 基线数据
const baselines = ref([])

// 计算属性
const filteredBaselines = computed(() => {
  return baselines.value.filter(baseline => {
    // 名称搜索
    const matchesName = searchForm.value.name === '' || 
      baseline.name.toLowerCase().includes(searchForm.value.name.toLowerCase());
    
    // 类型过滤
    const matchesType = searchForm.value.type === '' || baseline.type === searchForm.value.type;
    
    // 状态过滤
    const matchesStatus = searchForm.value.status === '' || baseline.status === searchForm.value.status;
    
    return matchesName && matchesType && matchesStatus;
  });
});

const totalBaselines = computed(() => baselines.value.length);
const activeBaselines = computed(() => baselines.value.filter(b => b.status === 'active').length);
const compliantSystems = computed(() => 76); // 模拟数据
const pendingTasks = computed(() => 3); // 模拟数据

// 辅助函数
function getTypeName(type) {
  const typeMap = {
    'os': '操作系统',
    'database': '数据库',
    'web_server': 'Web服务器',
    'application': '应用服务',
    'network_device': '网络设备'
  };
  return typeMap[type] || type;
}

function getTypeTagType(type) {
  const typeMap = {
    'os': 'primary',
    'database': 'success',
    'web_server': 'warning',
    'application': 'info',
    'network_device': 'danger'
  };
  return typeMap[type] || 'default';
}

function getStatusName(status) {
  const statusMap = {
    'active': '活跃',
    'disabled': '禁用',
    'expired': '已过期'
  };
  return statusMap[status] || status;
}

function getStatusTagType(status) {
  const statusMap = {
    'active': 'success',
    'disabled': 'info',
    'expired': 'danger'
  };
  return statusMap[status] || 'default';
}

function getSeverityName(severity) {
  const severityMap = {
    'critical': '严重',
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  };
  return severityMap[severity] || severity;
}

function getSeverityTagType(severity) {
  const severityMap = {
    'critical': 'danger',
    'high': 'warning',
    'medium': 'info',
    'low': 'success'
  };
  return severityMap[severity] || 'default';
}

// 方法函数
function refreshBaselines() {
  loading.value = true;
  setTimeout(() => {
    baselines.value = [...mockBaselines];
    loading.value = false;
  }, 500);
}

function handleSearch() {
  // 搜索逻辑已在计算属性中实现
  currentPage.value = 1;
}

function resetSearch() {
  searchForm.value = {
    name: '',
    type: '',
    status: ''
  };
  currentPage.value = 1;
}

function handleSelectionChange(val) {
  selectedBaselines.value = val;
}

function handleBatchAction(action) {
  if (selectedBaselines.value.length === 0) {
    ElMessage.warning('请先选择要操作的基线');
    return;
  }

  switch (action) {
    case 'activate':
      batchActivateBaselines();
      break;
    case 'deactivate':
      batchDeactivateBaselines();
      break;
    case 'delete':
      batchDeleteBaselines();
      break;
    case 'export':
      batchExportBaselines();
      break;
  }
}

function batchActivateBaselines() {
  ElMessageBox.confirm(
    `确定要激活选中的 ${selectedBaselines.value.length} 个基线吗？`,
    '确认激活',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    loading.value = true;
    setTimeout(() => {
      selectedBaselines.value.forEach(baseline => {
        const index = baselines.value.findIndex(b => b.id === baseline.id);
        if (index > -1) {
          baselines.value[index].status = 'active';
        }
      });
      selectedBaselines.value = [];
      loading.value = false;
      ElMessage.success(`已成功激活 ${selectedBaselines.value.length} 个基线`);
    }, 500);
  }).catch(() => {
    // 取消操作
  });
}

function batchDeactivateBaselines() {
  ElMessageBox.confirm(
    `确定要禁用选中的 ${selectedBaselines.value.length} 个基线吗？`,
    '确认禁用',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    loading.value = true;
    setTimeout(() => {
      selectedBaselines.value.forEach(baseline => {
        const index = baselines.value.findIndex(b => b.id === baseline.id);
        if (index > -1) {
          baselines.value[index].status = 'disabled';
        }
      });
      selectedBaselines.value = [];
      loading.value = false;
      ElMessage.success(`已成功禁用 ${selectedBaselines.value.length} 个基线`);
    }, 500);
  }).catch(() => {
    // 取消操作
  });
}

function batchDeleteBaselines() {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedBaselines.value.length} 个基线吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    loading.value = true;
    setTimeout(() => {
      selectedBaselines.value.forEach(baseline => {
        const index = baselines.value.findIndex(b => b.id === baseline.id);
        if (index > -1) {
          baselines.value.splice(index, 1);
        }
      });
      selectedBaselines.value = [];
      loading.value = false;
      ElMessage.success(`已成功删除 ${selectedBaselines.value.length} 个基线`);
    }, 500);
  }).catch(() => {
    // 取消操作
  });
}

function batchExportBaselines() {
  // 模拟导出操作
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    ElMessage.success(`已成功导出 ${selectedBaselines.value.length} 个基线`);
  }, 1000);
}

function viewBaselineDetails(baseline) {
  currentBaseline.value = JSON.parse(JSON.stringify(baseline));
  baselineDetailsVisible.value = true;
}

function closeBaselineDetails() {
  currentBaseline.value = null;
  baselineDetailsVisible.value = false;
}

function createBaseline() {
  resetBaselineForm();
  isEditing.value = false;
  createEditVisible.value = true;
}

function editBaseline(baseline) {
  baselineForm.value = JSON.parse(JSON.stringify(baseline));
  isEditing.value = true;
  createEditVisible.value = true;
}

function resetBaselineForm() {
  baselineForm.value = {
    id: '',
    name: '',
    type: '',
    description: '',
    version: '1.0',
    supportedPlatforms: [],
    controls: []
  };
}

function closeCreateEdit() {
  resetBaselineForm();
  createEditVisible.value = false;
}

function saveBaseline() {
  formLoading.value = true;
  setTimeout(() => {
    if (isEditing.value) {
      // 更新基线
      const index = baselines.value.findIndex(b => b.id === baselineForm.value.id);
      if (index > -1) {
        baselines.value[index] = { ...baselineForm.value, lastUpdated: new Date().toLocaleString('zh-CN') };
        ElMessage.success('基线更新成功');
      }
    } else {
      // 创建新基线
      const newBaseline = {
        ...baselineForm.value,
        id: `BASELINE-${baselineForm.value.type.toUpperCase().replace('_', '-')}-${String(baselines.value.length + 1).padStart(3, '0')}`,
        controlsCount: baselineForm.value.controls.length,
        status: 'active',
        createdAt: new Date().toLocaleString('zh-CN'),
        lastUpdated: new Date().toLocaleString('zh-CN'),
        createdBy: '当前用户' // 实际应用中应从登录信息获取
      };
      baselines.value.unshift(newBaseline);
      ElMessage.success('基线创建成功');
    }
    formLoading.value = false;
    closeCreateEdit();
  }, 1000);
}

function addControl() {
  baselineForm.value.controls.push({
    id: `CTRL-${baselineForm.value.type.toUpperCase().replace('_', '-')}-${String(baselineForm.value.controls.length + 1).padStart(3, '0')}`,
    name: '',
    severity: 'medium',
    description: '',
    checkMethod: '',
    remediation: ''
  });
}

function editControl(control) {
  // 实际应用中可能需要打开一个编辑控制项的对话框
  ElMessage.info('编辑控制项功能将在后续版本中实现');
}

function removeControl(index) {
  baselineForm.value.controls.splice(index, 1);
}

function deployBaseline(baseline) {
  currentBaseline.value = baseline;
  resetDeployForm();
  deployBaselineVisible.value = true;
}

function resetDeployForm() {
  deployForm.value = {
    targetSystems: [],
    deployMode: 'audit',
    executeOption: 'immediate',
    scheduledTime: null
  };
}

function confirmDeploy() {
  deployLoading.value = true;
  setTimeout(() => {
    deployLoading.value = false;
    deployBaselineVisible.value = false;
    ElMessage.success('基线部署任务已成功提交');
  }, 1500);
}

function viewCompliance(baseline) {
  complianceResultBaselineName.value = baseline.name;
  // 模拟加载合规性检查结果
  complianceResult.value = {
    checkTime: new Date().toLocaleString('zh-CN'),
    targetSystem: 'Web服务器-01',
    totalChecks: 156,
    compliantChecks: 112,
    nonCompliantChecks: 44,
    complianceRate: 71.8,
    checkDetails: [
      {
        controlId: 'CTRL-OS-001',
        controlName: '启用Windows防火墙',
        status: 'compliant',
        actualValue: '已启用',
        expectedValue: '已启用',
        severity: 'critical',
        remediation: '无需操作'
      },
      {
        controlId: 'CTRL-OS-002',
        controlName: '配置账户锁定策略',
        status: 'non_compliant',
        actualValue: '未设置',
        expectedValue: '阈值:5次,锁定时间:30分钟',
        severity: 'high',
        remediation: '修改账户锁定策略设置'
      },
      // 更多检查结果...
    ]
  };
  complianceResultVisible.value = true;
  
  // 在对话框显示后初始化图表
  setTimeout(() => {
    initComplianceChart();
  }, 100);
}

function initComplianceChart() {
  if (!complianceChart.value || !complianceResult.value) return;
  
  const chart = echarts.init(complianceChart.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      left: 'center'
    },
    series: [
      {
        name: '合规性检查',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: complianceResult.value.compliantChecks,
            name: '合规项',
            itemStyle: { color: '#67c23a' }
          },
          {
            value: complianceResult.value.nonCompliantChecks,
            name: '不合规项',
            itemStyle: { color: '#f56c6c' }
          }
        ]
      }
    ]
  };
  
  chart.setOption(option);
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chart.resize();
  });
}

function exportComplianceReport() {
  ElMessage.success('合规性报告导出成功');
}

function remediateNonCompliant() {
  ElMessageBox.confirm(
    '确定要自动修复所有不合规项吗？此操作可能会修改系统配置。',
    '确认修复',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
      ElMessage.success('自动修复已开始，稍后可查看修复结果');
    }, 1500);
  }).catch(() => {
    // 取消操作
  });
}

function importBaseline() {
  ElMessage.info('导入基线功能将在后续版本中实现');
}

function exportBaseline(baseline) {
  ElMessage.success(`基线 "${baseline.name}" 导出成功`);
}

function cloneBaseline(baseline) {
  const clonedBaseline = JSON.parse(JSON.stringify(baseline));
  clonedBaseline.id = `BASELINE-${clonedBaseline.type.toUpperCase().replace('_', '-')}-${String(baselines.value.length + 1).padStart(3, '0')}`;
  clonedBaseline.name = `${clonedBaseline.name} (克隆)`;
  clonedBaseline.version = '1.0';
  clonedBaseline.createdAt = new Date().toLocaleString('zh-CN');
  clonedBaseline.lastUpdated = new Date().toLocaleString('zh-CN');
  clonedBaseline.createdBy = '当前用户';
  clonedBaseline.status = 'active';
  
  baselines.value.unshift(clonedBaseline);
  ElMessage.success('基线克隆成功');
}

function deleteBaseline(baseline) {
  ElMessageBox.confirm(
    `确定要删除基线 "${baseline.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    const index = baselines.value.findIndex(b => b.id === baseline.id);
    if (index > -1) {
      baselines.value.splice(index, 1);
      ElMessage.success('基线删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
}

// 生命周期钩子
onMounted(() => {
  refreshBaselines();
});

// 暴露给模板的数据和方法
defineExpose({
  // 响应式数据
  baselines,
  loading,
  searchForm,
  currentPage,
  pageSize,
  selectedBaselines,
  baselineDetailsVisible,
  currentBaseline,
  createEditVisible,
  isEditing,
  deployBaselineVisible,
  complianceResultVisible,
  complianceResultBaselineName,
  complianceResult,
  complianceChart,
  baselineForm,
  baselineFormRules,
  deployForm,
  deployFormRules,
  availablePlatforms,
  availableSystems,
  formLoading,
  deployLoading,
  
  // 计算属性
  filteredBaselines,
  totalBaselines,
  activeBaselines,
  compliantSystems,
  pendingTasks,
  
  // 方法
  refreshBaselines,
  handleSearch,
  resetSearch,
  handleSelectionChange,
  handleBatchAction,
  viewBaselineDetails,
  closeBaselineDetails,
  createBaseline,
  editBaseline,
  closeCreateEdit,
  saveBaseline,
  addControl,
  editControl,
  removeControl,
  deployBaseline,
  confirmDeploy,
  viewCompliance,
  exportComplianceReport,
  remediateNonCompliant,
  importBaseline,
  exportBaseline,
  cloneBaseline,
  deleteBaseline,
  getTypeName,
  getTypeTagType,
  getStatusName,
  getStatusTagType,
  getSeverityName,
  getSeverityTagType
});
</script>

<style>
@import '../assets/compliance-style.css';
</style>